<template>
  <div class="product-choose">
    <div
      v-if="!relativeType"
      class="handel-header">
      <el-popover
        v-model="showPopover"
        :disabled="popoverDisabled"
        placement="right-start"
        width="700"
        popper-class="no-padding-popover"
        trigger="click">

        <relative-card
          v-model="showPopover"
          :request-config="requestConfig"
          :default-value="productList"
          primary-key="productId"
          label="选择产品"
          @close="showPopover = !showPopover"
          @confirm="handleRelativeConfirm" />

        <el-button
          slot="reference"
          type="primary"
          size="mini"
          class="xr-btn--primary"
          @click="handleToShowPopover">
          添加产品
        </el-button>
      </el-popover>
    </div>

    <el-table
      :data="productList"
      style="width: 100%;">
      <template v-for="(field, index) in fieldList">
        <el-table-column
          :key="index"
          :prop="field.prop"
          :label="field.label"
          show-overflow-tooltip />
      </template>
      <el-table-column label="出库数量">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.num"
            :controls="false"
            :precision="2"
            :min="0"
            :max="scope.row.maxNum"
            placeholder="请输入"
            @change="totalPriceChange" />
        </template>
      </el-table-column>
      <el-table-column label="备注">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.remarks"
            :maxlength="100"
            placeholder="请输入"
            @change="totalPriceChange" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click.stop="removeItem(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
/**
 * Create by yxk at 2020/6/10
 */
import { jxcWarehouseProductQueryPageListAPI } from '@/api/jxc/storage'
import { jxcOutboundQueryEdProductListAPI } from '@/api/jxc/outbound'

import RelativeCard from '../../RelativeCard'
import JxcTypes from '../../../jxcTypes'
import { objDeepCopy } from '@/utils'

export default {
  name: 'OutboundChoose',
  components: {
    RelativeCard
  },
  props: {
    relativeData: {
      type: Object,
      default: () => {}
    },
    relativeType: {
      type: String,
      default: null
    },
    defaultValue: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      showPopover: false,

      fieldList: [
        { label: '产品名称', prop: 'productName', width: null },
        { label: '产品规格', prop: 'spDataValue', width: null },
        { label: '产品单位', prop: 'productCompany', width: null },
        { label: '库存数量', prop: 'remainingQuantity', width: null },
        { label: '出库总量', prop: 'saleProductNumber', width: null },
        { label: '已出库', prop: 'outboundProductNumber', width: null }
      ],
      productList: [],
      totalPrice: 0,
      totalCount: 0
    }
  },
  computed: {
    requestConfig() {
      return {
        fieldList: [
          { fieldName: 'productName', name: '产品名称', fixed: 'left' },
          { fieldName: 'spDataValue', name: '规格' },
          { fieldName: 'productCompany', name: '单位' },
          { fieldName: 'productType', name: '产品类型' },
          { fieldName: 'remainingQuantity', name: '库存量' },
          { fieldName: 'warehouseName', name: '所属仓库' }
        ],
        listRequest: jxcWarehouseProductQueryPageListAPI,
        listParams: {
          label: JxcTypes.jxc_product.label,
          warehouseId: (this.relativeData && this.relativeData.warehouseId) ? this.relativeData.warehouseId : '',
          stock: '1'
          // searchList: [{
          //   formType: 'text',
          //   type: 1,
          //   name: 'product_ishelf', // 上架的产品
          //   values: [1]
          // }]
        },
        placeholder: '请输入产品名称',
        searchParamsFn: (params, keyword) => {
          return {
            ...params,
            productName: keyword || ''
          }
        }
      }
    },

    popoverDisabled() {
      return !this.relativeData || !this.relativeData.warehouseId
    }
  },
  watch: {
    defaultValue: {
      handler(val) {
        if (val.length > 0) {
          this.productList = objDeepCopy(val)
        }
      },
      deep: true,
      immediate: true
    },
    relativeType: {
      handler(val) {
        this.productList = []
        if (!val) return
        this.getProductList()
      },
      immediate: true
    },
    relativeData: {
      handler(val) {
        this.productList = []
        if (!val) return
        this.getProductList()
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    handleToShowPopover() {
      if (this.popoverDisabled) {
        this.$message.error('请先选择出库仓')
        this.showPopover = false
      }
    },
    getProductList() {
      console.log('config:----', this.relativeData, this.relativeType)
      if (!this.relativeData ||
        !this.relativeData.orderId ||
        !this.relativeData.warehouseId ||
        !this.relativeType) return

      jxcOutboundQueryEdProductListAPI({
        orderId: this.relativeData.orderId,
        warehouseId: this.relativeData.warehouseId,
        receiptType: this.relativeType === 'sale_cause' ? '销售出库' : '采购退货出库'
      }).then(res => {
        console.log('res: ', res.data)
        this.productList = res.data.map(o => {
          const maxNum = o.weiNumber > o.remainingQuantity ? o.remainingQuantity : o.weiNumber
          return {
            ...o,
            num: maxNum > o.weiNumber ? o.weiNumber : maxNum,
            maxNum: maxNum,
            remarks: ''
          }
        })
        this.totalPriceChange()
      }).catch(() => {
        this.productList = []
      })
    },

    handleRelativeConfirm(data) {
      // console.log('data', data)
      // console.log('productList', this.productList)
      const dataIds = data.valData
      // 去掉被删除的产品
      const productList = this.productList.filter(o => dataIds.includes(o.productId))
      // 过滤掉已经添加过的产品
      const ids = this.productList.map(o => o.productId)
      const list = data.data.filter(o => !ids.includes(o.productId)).map(o => {
        return {
          productCode: o.productCode,
          productCompany: o.productCompany,
          productId: o.productId,
          productName: o.productName,
          spDataValue: o.spDataValue,
          weiNumber: o.remainingQuantity,
          remainingQuantity: o.remainingQuantity,
          outboundProductNumber: 0,
          saleProductNumber: o.remainingQuantity,
          num: o.remainingQuantity,
          remarks: '',
          relationId: '',
          maxNum: o.remainingQuantity
        }
      })
      this.productList = [...productList, ...list]
      this.showPopover = false
      this.totalPriceChange()
    },

    removeItem(index) {
      this.productList.splice(index, 1)
      this.totalPriceChange()
    },

    totalPriceChange() {
      this.$emit('change', {
        data: this.productList,
        total: 0
      })
    }
  }
}
</script>

<style scoped lang="scss">
  @import "index";
</style>
